package com.kuangstudy.thread.deadlock;

/**
 * @author Losca
 * @date 2021/7/20 22:56
 * 死锁
 */
public class Demo {
    public static void main(String[] args) {
        Makeup m1 = new Makeup(0, "白雪公主");
        Makeup m2 = new Makeup(1, "皇后");
        m1.start();
        m2.start();
        /**
         *  解除死锁
         *  synchronized拿出来即可
         *  皇后获取镜子资源
         * 白雪公主获取口红资源
         * 皇后获取口红资源
         * 白雪公主获取镜子资源
         */

    }

}

/**
 * 口红
 */
class Lipstick {

}

/**
 * 镜子
 */
class Mirror {

}

/**
 * 化妆
 */
class Makeup extends Thread {
    //static静态字确保只有一个
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();
    //选择
    int choice;
    //女孩名字
    String girlName;

    public Makeup(int choice, String girlName) {
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
        makeUp();
    }

    //化妆 互相持有对方的锁
    private void makeUp() {
        if (choice == 0) {
            //获得口红资源
            synchronized (lipstick) {
                System.out.println(this.girlName + "获取口红资源");
                //一秒钟后想获取镜子资源
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            synchronized (mirror) {
                System.out.println(this.girlName + "获取镜子资源");
            }
        } else {
            //获得镜子资源
            synchronized (mirror) {
                System.out.println(this.girlName + "获取镜子资源");
                //两秒钟后想获取口红资源
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            synchronized (lipstick) {
                System.out.println(this.girlName + "获取口红资源");
            }
        }
    }
}


